<template>
    <div class="right-board">
    <el-tabs v-model="currentTab" class="center-tabs">
      <el-tab-pane label="配置" name="field" />
      <el-tab-pane label="数据" name="data" />
      <el-tab-pane label="参数" name="location" />
    </el-tabs>
    <div class="field-box">
      
      <el-scrollbar class="right-scrollbar">
        <!-- 组件属性 -->
        
        <el-form v-show="currentTab==='field'" size="small" label-width="90px">
        <el-collapse  v-model="activeNames" accordion>
          <el-collapse-item title="图层" name="1">
            <el-form-item v-if="configData.layerName!==undefined" label="图层名称">
              <el-input v-model="configData.layerName" placeholder="请输入图层名称" />
            </el-form-item>
          </el-collapse-item>
          <el-collapse-item title="表格列" name="2">
            <draggable
              
              :animation="340"
              group="selectItem"
              handle=".option-drag"
            >  
            <div style="display:flex">
              <el-form-item label="列名"></el-form-item>
              <el-form-item label="列值" style="margin-left: 60px;"></el-form-item>
            </div>
            
            
              <div v-for="(item, index) in cols" :key="index" class="select-item">
                
                  <el-input v-model="item.title" placeholder="列名" size="small"   @blur.prevent="changeCols()"/>
                  
                
                <div class="close-btn select-line-icon" @click="removeSelectItem(index)">
                  <i class="el-icon-remove-outline" />
                </div>
              </div>
             </draggable>
            <div style="margin-left: 20px;">
              <el-button style="padding-bottom: 0" icon="el-icon-circle-plus-outline" type="text" @click="addSelectItem">
                添加列
              </el-button>
            </div> 
            
          </el-collapse-item>

          <el-collapse-item title="表格设置" name="3">
            <el-form-item label="固定左边列数">
              <el-input-number v-model="configData.chartOption.fixedColumnsLeft" controls-position="right" :min="0" :step="1"></el-input-number>
            </el-form-item>

            <el-form-item label="固定上边列数">
              <el-input-number v-model="configData.chartOption.fixedRowsTop" controls-position="right" :min="0" :step="1"></el-input-number>
            </el-form-item>

            <el-form-item v-if="configData.chartOption.autoWrapRow!==undefined" label="是否自动换行">
              <el-switch v-model="configData.chartOption.autoWrapRow" />
            </el-form-item>

            <el-form-item v-if="configData.chartOption.colHeaders!==undefined" label="是否显示表头">
              <el-switch v-model="configData.chartOption.colHeaders" />
            </el-form-item>

            <el-form-item v-if="configData.chartOption.rowHeaders!==undefined" label="是否显示行号">
              <el-switch v-model="configData.chartOption.rowHeaders" />
            </el-form-item>

            <el-form-item v-if="configData.chartOption.readonly!==undefined" label="是否只读">
              <el-switch v-model="configData.chartOption.readonly" />
            </el-form-item>

          </el-collapse-item>
          

           
          <el-collapse-item title="动画" name="6">
            <el-form-item v-if="configData.chartOption.animate!==undefined" label="载入动画">
              <el-select v-model="configData.chartOption.animate" placeholder="请选择">
                <el-option
                  v-for="item in animateOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>
          </el-collapse-item>
        </el-collapse>

        </el-form>
        <!-- 表单属性 -->
        <el-form v-show="currentTab === 'data'" size="small" label-width="90px">
          <el-form-item v-if="" label="数据源类型">
            <el-select v-model="configData.chartOption.dataSourceType" placeholder="请选择">
                <el-option
                  v-for="item in dataSourceOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'static'" label="静态数据值" prop="desc">
            <el-input type="textarea" :rows="20" v-model="staticDataValue"  @blur.prevent="changeStaticData()"></el-input>
          </el-form-item>

          <!-- <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="接口地址">
            <el-input type="textarea" :rows="5" placeholder="请输入接口地址" v-model="interfaceUrl" @blur.prevent="changeInterfaceUrl()">
            </el-input>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="请求方式">
            <el-radio-group v-model="configData.chartOption.requestMethod">
              <el-radio label="GET"></el-radio>
              <el-radio label="POST"></el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="请求参数">
            <el-input type="textarea" :rows="5" placeholder="请输入请求参数" v-model="requestParameters" @blur.prevent="changeRequestParameters()">
            </el-input>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'url'" label="刷新时间">
            <el-input-number v-model="configData.chartOption.timeout" controls-position="right"  :step="1000"></el-input-number>
          </el-form-item>-->

          <api-source v-show="configData.chartOption.dataSourceType === 'url'" 
            :interfaceUrl="interfaceUrl" 
            :requestMethod="configData.chartOption.requestMethod"
            :requestParameters="configData.chartOption.requestParameters"
            :token="configData.chartOption.token"
            :timeout="configData.chartOption.timeout"
            @changeApi="changeApi" ></api-source>          

          <!-- <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="数据库类型">
            <el-select v-model="configData.chartOption.database.type" placeholder="请选择">
                <el-option
                  v-for="item in dataBaseOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
                </el-option>
              </el-select>
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="IP地址">
            <el-input v-model="database.ipAdress" placeholder="请输入数据库IP地址" />
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="端口">
            <el-input v-model="database.port" placeholder="请输入端口" />
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="数据库名称">
            <el-input v-model="database.baseName" placeholder="请输入数据库名称" />
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="用户名">
            <el-input v-model="database.username" placeholder="请输入用户名" />
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="密码">
            <el-input type="password" v-model="database.password" placeholder="请输入密码" />
          </el-form-item> -->

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="选择已有数据源">
              <div style="display:flex">
                <el-select v-model="database.dataSourceId" placeholder="请选择">
                  <el-option
                    v-for="item in sourseList"
                    :key="item.id"
                    :label="item.linkName"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button type="primary" @click="addSourse" style="margin-left:10px">新建</el-button>
              </div>
              
          </el-form-item>

          <el-form-item v-show="configData.chartOption.dataSourceType === 'database'" label="">
            <el-button type="primary" @click="linkDB">连接数据库</el-button>
          </el-form-item>


        </el-form>
        <!-- 组件位置 -->
        <el-form v-show="currentTab === 'location'" size="small" label-width="90px">
          <el-form-item label="X位置">
            <el-input-number v-model="configData.x" controls-position="right"  :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="y位置">
            <el-input-number v-model="configData.y" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="宽度">
            <el-input-number v-model="configData.width" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
          <el-form-item label="高度">
            <el-input-number v-model="configData.height" controls-position="right" :step="1"></el-input-number>
          </el-form-item>
        </el-form>
      </el-scrollbar>
    </div>
    <!--分析配置页-->
    <el-dialog title="数据分析配置" v-if="dbVisble" :visible.sync="dbVisble" width="1000px" append-to-body>
      
      <el-form :model="bi" ref="bi" :inline="true" label-width="68px" v-loading="loading">
        <el-row :gutter="15">
        <el-col :span="24">
          <el-form-item label="目标表">
            <el-select v-model="database.tableName" placeholder="请选择" @change="tableSelectChanged">
                  <el-option
                    v-for="item in tableOptions"
                    :key="item.table_name"
                    :label="item.table_name"
                    :value="item.table_name">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>
        </el-row>

        <el-row :gutter="15">
        <el-col :span="16">
          <el-form-item v-show="database.tableName !== ''" label="展示字段">
            <el-select v-model="bi.coordinate.filter.value" multiple filterable placeholder="请选择" style="width:400px">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        </el-row>

        <el-row :gutter="15">
          <el-col :span="16">
            <el-form-item v-show="database.tableName !== ''" label="分组字段">
              <el-select v-model="bi.group.field" multiple filterable placeholder="请选择" style="width:400px">
                    <el-option
                      v-for="item in fieldOptions"
                      :key="item.id"
                      :label="item.label"
                      :value="item.id">
                    </el-option>
                  </el-select>
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="15">
        <el-col :span="14">
          <el-form-item v-show="database.tableName !== ''" label="排序字段">
            <el-select v-model="bi.order.field" multiple filterable placeholder="请选择" style="width:400px">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item v-show="bi.order.field.length > 0" label="排序方式">
            <el-select v-model="bi.order.filter.type" placeholder="请选择">
              <el-option label="正序" value="asc"></el-option>
              <el-option label="倒序" value="desc"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        </el-row>

        <el-row v-show="database.tableName !== ''">
          <el-col :span="24">
            <el-form-item label="筛选条件" class="screen">
              <div style="height:200px;overflow:auto">
              <div v-show="database.tableName !== ''" style="display: flex">
                <el-form-item label="关联关系" style="margin-left: 70px;"></el-form-item>
                <el-form-item label="字段" style="margin-left: 110px;"></el-form-item>
                <el-form-item label="条件" style="margin-left: 110px;"></el-form-item>
                <el-form-item label="值" style="margin-left: 110px;"></el-form-item>
              </div>
              <div v-for="(item, index) in bi.conditions" :key="index" class="select-item">
                <el-select v-model="item.relation" placeholder="请选择" style="width: 197px">
                    <el-option label="与" value="and"></el-option>
                    <el-option label="或" value="or"></el-option>
                </el-select>
                <el-select v-model="item.field" placeholder="请选择" style="width: 197px">
                  <el-option
                    v-for="item in fieldOptions"
                    :key="item.id"
                    :label="item.label"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-select v-model="item.condition" placeholder="请选择" style="width: 197px">
                  <el-option
                    v-for="item in conditionOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
                <el-input v-model="item.value" placeholder="值" style="width: 197px"/>

                <div class="close-btn select-line-icon" @click="removeDatabaseSelectItem(index)">
                  <i class="el-icon-remove-outline" />
                </div>

              </div>
              <div style="margin-left: 20px;">
                <el-button style="padding-bottom: 0" icon="el-icon-circle-plus-outline" type="text" @click="addDatabaseSelectItem">
                  添加列
                </el-button>
              </div>
            </div>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAnalysis">提交</el-button>
        <!--<el-button @click="cancelUpload">取 消</el-button>-->
      </div>
    </el-dialog>
    <!-- 添加数据源配置对话框 -->
    <el-dialog title="新增数据源" v-if="sourseOpen" :visible.sync="sourseOpen" width="520px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库类型" prop="databaseType" label-width="100px">
          <!-- <el-input v-model="form.databaseType" placeholder="请输入数据库类型" /> -->
          <el-select v-model="form.databaseType" placeholder="请选择数据库类型">
            <el-option label="MySQL" value="mysql"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="连接名称" prop="linkName" label-width="100px">
          <el-input v-model="form.linkName" placeholder="请输入链接名称" />
        </el-form-item>
        <el-form-item label="IP地址" prop="ipAddress" label-width="100px">
          <el-input v-model="form.ipAddress" placeholder="请输入IP地址" />
        </el-form-item>
        <el-form-item label="端口" prop="port" label-width="100px">
          <el-input v-model="form.port" placeholder="请输入端口号"/>
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName" label-width="100px">
          <el-input v-model="form.databaseName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="用户名" prop="username" label-width="100px">
          <el-input v-model="form.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" label-width="100px">
          <el-input type="password" v-model="form.password" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="备注" label-width="100px">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>

import {animateOptions} from '../../animate/animate'
import { dataSourceOptions, dataBaseOptions, statisticsTypeOptions, filterTypeOptions, conditionOptions } from '../../ComponentsConfig'
import { getAllTable, getAllField, getDistinctOneField } from '@/api/tool/datav/chartDB'
import { listSourse, getSourse, addSourse } from '@/api/tool/datav/sourse'
import VueEvent from '@/views/tool/datav/VueEvent'
import draggable from 'vuedraggable'
import ApiSource from './chartDB/ApiSource'

const BIBAR = {
        //图例数据分析结构
        legend: {
          field: '',
          filter: {
            options: [],
            type: '',
            value: ''
          }
        },
        //坐标数据分析结构
        coordinate: {
          field: '',
          filter: {
            options: [],
            type: '',
            value: ''
          }
        },
        //统计数据分析结构
        statistics: {
          field: '',
          //统计类型：计数：count；求和：sum。默认计数
          type: 'count',
          filter: {
            options: [],
            type: '',
            value: ''
          }
        },
        //分组数据分析结构
        group: {
          field: ''
        },
        //排序数据分析结构
        order: {
          field: '',
          filter: {
            options: [],
            type: 'asc',
            value: ''
          }
        },
        //条件
        conditions: []
      };
export default {
  components: {
    draggable,
    ApiSource
  },
  props: ["costomData"],
  data() {
    return {
      fontFamilys:this.fontFamilys,
      activeNames: ['1'],
      currentTab: 'field',
      configData: this.costomData,
      animateOptions,
      dataSourceOptions,
      dataBaseOptions,
      statisticsTypeOptions,
      filterTypeOptions,
      conditionOptions,
      cols: JSON.parse(JSON.stringify(this.costomData.chartOption)).cols,
      staticDataValue: this.costomData != null ? JSON.stringify(this.costomData.chartOption.staticDataValue) : '',
      interfaceUrl: this.costomData.chartOption.interfaceURL != '' ? this.costomData.chartOption.interfaceURL : '',
      requestParameters: this.costomData.chartOption.requestParameters != '' ? this.costomData.chartOption.requestParameters : '',
      database: {
        type: this.costomData.chartOption.database.type,
        ipAdress: this.costomData.chartOption.database.ipAdress,
        port: this.costomData.chartOption.database.port,
        baseName: this.costomData.chartOption.database.baseName,
        username: this.costomData.chartOption.database.username,
        password: this.costomData.chartOption.database.password,
        tableName: this.costomData.chartOption.database.tableName,
        dataSourceId : this.costomData.chartOption.database.dataSourceId,
        fieldName: '',
        executeSql:'',
        chartStucture: {
          legend:[],
          coordinate:[],
          order:[],
          group:[],
          statisticsType: ''
        }
      },
      bi: null,
      //选择目标数据表集合
      tableOptions: [],
      //选择目标字段集合
      fieldOptions: [],
      dbVisble: false,
      loading: true,
      sourseList:[],
       // 表单参数
      form: {},
      // 表单校验
      rules: {
        databaseType: [
          { required: true, message: "数据库类型不能为空", trigger: "blur" }
        ],
        ipAddress: [
          { required: true, message: "ip地址不能为空", trigger: "blur" }
        ],
        port: [
          { required: true, message: "端口号不能为空", trigger: "blur" }
        ],
        databaseName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" }
        ],
        linkName: [
          { required: true, message: "链接名称不能为空", trigger: "blur" }
        ],
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ]
      },
      sourseOpen: false
    }
  },
  //页面加载完执行
  mounted() {
    this.getSourseList();
  },
  computed: {
    
  },
  watch: {
    configData: {
      deep: true,
      handler(newVal) {
        this.$emit("costom-change", newVal);
      }
    },
    costomData: {
      deep: true,
      handler(newVal) {
        this.configData = newVal;
        this.staticDataValue = JSON.stringify(newVal.chartOption.staticDataValue);
        this.interfaceUrl = newVal.chartOption.interfaceURL;
        this.requestParameters = newVal.chartOption.requestParameters;
        //分析动态连接数据库结构
        this.database.type = newVal.chartOption.database.type != undefined ? newVal.chartOption.database.type : '';
        this.database.ipAdress = newVal.chartOption.database.ipAdress != undefined ? newVal.chartOption.database.ipAdress : '';
        this.database.port = newVal.chartOption.database.port != undefined ? newVal.chartOption.database.port : '';
        this.database.baseName = newVal.chartOption.database.baseName != undefined ? newVal.chartOption.database.baseName : '';
        this.database.username = newVal.chartOption.database.username != undefined ? newVal.chartOption.database.username : '';
        this.database.password = newVal.chartOption.database.password != undefined ? newVal.chartOption.database.password : '';
        //this.database.tableName = newVal.chartOption.database.tableName != undefined ? newVal.chartOption.database.tableName : '';
        this.database.executeSql = newVal.chartOption.database.executeSql != undefined ? newVal.chartOption.database.executeSql : '';
        if (newVal.chartOption.database.chartStucture != undefined) {
          this.database.chartStucture = newVal.chartOption.database.chartStucture;
        }
        if (newVal.chartOption.bi != undefined && newVal.chartOption.bi != null) {
          this.bi = newVal.chartOption.bi;
        } else {
          this.bi = JSON.parse(JSON.stringify( BIBAR ));
        }
      }
    },
    'costomData.chartOption.database.baseName': {
      handler(val) {
        this.bi = JSON.parse(JSON.stringify( BIBAR ));
        this.$set(this.database, 'tableName', '');
      }
    },
  },
  methods: {
    changeStaticData() {
      //如果是静态数据就给staticDataValue赋值
      if (this.configData.chartOption.isStaticData == true) {
          //this.configData.staticDataValue = JSON.parse(this.staticDataValue);
          this.$set(this.configData.chartOption, 'staticDataValue', JSON.parse(this.staticDataValue));
      } else {
          //this.configData.interfaceURL = this.staticDataValue;
          this.$set(this.configData.chartOption, 'staticDataValue', this.staticDataValue);
      }
    },
    changeInterfaceUrl() {
      this.$set(this.configData.chartOption, 'interfaceURL', this.interfaceUrl);
    },
    changeRequestParameters() {
      this.$set(this.configData.chartOption, 'requestParameters', this.requestParameters);
    },
    changeApi(val){
      if(val.type == "interfaceUrl"){
        this.$set(this.configData.chartOption, 'interfaceURL', val.arr);
      }else if(val.type == "requestParameters"){
        this.$set(this.configData.chartOption, 'requestParameters', val.arr);
      }else if(val.type == "requestMethod"){
        this.$set(this.configData.chartOption, 'requestMethod', val.arr);
      }else if(val.type == "token"){
        this.$set(this.configData.chartOption, 'token', val.arr);
      }else if(val.type == "timeout"){
        this.$set(this.configData.chartOption, 'timeout', val.arr);
      }
    },    
    addSelectItem(){
      this.cols.push({
        title: ''
      })
    },
    removeSelectItem(index){
      let newCols = this.cols;
      newCols.splice(index, 1);
      this.$set(this.configData.chartOption, 'cols',JSON.parse(JSON.stringify( newCols)));

    },
    changeCols(){
      this.$set(this.configData.chartOption, 'cols',JSON.parse(JSON.stringify( this.cols)));
    },
    changeState(){
      this.cols = []
      this.$set(this.configData.chartOption, 'cols', []);
    },
    DBConn() {
      console.log("bi=>", this.bi);
      //连接数据库
      getAllTable(this.database).then(response => {
          if (response.code == 200) {
              //alert("连接数据库成功");
              this.$message({
                  message: '连接数据库成功',
                  type: 'success'
              });
              console.log(response.data);
              this.tableOptions = response.data;
              this.loading = false;
              this.dbVisble = true;
              this.$set(this.configData.chartOption, 'database', JSON.parse(JSON.stringify( this.database )));
              if(this.database.tableName != ""){
                this.tableSelectChanged(this.database.tableName)
              }
          } else {
              this.$message.error('连接数据库失败');
          }
      });

      //this.dbVisble = true;
      // this.$nextTick(() => {
      //   this.$refs.chartDbFactory.init();
      // })
    },
    tableSelectChanged(value) {
      console.log(value)
      this.$set(this.database, 'tableName', value);
      //获取数据库下所有字段
      getAllField(this.database).then(response => {
          if (response.code == 200) {
              //alert("连接数据库成功");
              // this.$message({
              //     message: '连接数据库成功',
              //     type: 'success'
              // });
              //console.log(response.data);
              let treeData = [];
              for (const item of response.data) {
                let o = new Object();
                o.id = item.columnName;
                o.label = item.columnName + "( " + item.comment + " )";
                treeData.push(o);
              }
              this.fieldOptions = treeData;
          } else {
              this.$message.error('获取数据库下所有字段失败');
          }
      });
    },
    addDatabaseSelectItem(){
      this.bi.conditions.push({
        relation: '',
        field: '',
        condition: '',
        value: ''
      })
    },
    removeDatabaseSelectItem(index){
      let newCols = this.bi.conditions;
      newCols.splice(index, 1);
    },
    submitAnalysis() {
      console.log(this.bi);
      let selectPart = "select ";
      let wherePart = " where 1=1 ";
      let orderByPart = " order by ";

      //selectPart = selectPart + this.bi.coordinate.field + " as zbwd, ";
      for (const item of this.bi.coordinate.filter.value) {
        selectPart += item + ",";
      }
      selectPart = selectPart.slice(0,-1);
      selectPart = selectPart + " from " + this.database.tableName;

      // 判断筛选条件是否为空
      if (this.bi.conditions) {
        for (const obj of this.bi.conditions) {
          //如果是空或null的条件不用拼接值字段
          if (obj.condition == "is null" || obj.condition == "is not null" || obj.condition == '= ""' || obj.condition == '!= ""' ){
              wherePart = wherePart + ' '+ obj.relation+' ' + obj.field + " " + obj.condition  
          }
          //如果是包含关系，先将可能输入的中文逗号换成英文逗号，再转成数组拼成分别用单引号包起来的字符串
          else if(obj.condition == "in" || obj.condition == "not in"){

            let valueArr = (obj.value.replace("，",",")).split(",");
            let linkResult = '';
            valueArr.forEach(element => {
              linkResult += "'" + element + "',";
            });
            
            linkResult = linkResult.slice(0,linkResult.length-1)

            wherePart = wherePart + ' '+ obj.relation+' ' + obj.field +' ' + obj.condition + "(" + linkResult + ")"
          }
          //其他关系直接拼接
          else{
              wherePart = wherePart + ' '+ obj.relation+' ' + obj.field+' ' + obj.condition + "'" + obj.value + "'"
          }
          
        }
      }
      let executeSql = selectPart + wherePart;

      //判断分组是否为空
      let groupByPart = " group by ";
      for (const item of this.bi.group.field) {
        groupByPart += item + ",";
      }
      groupByPart = groupByPart.slice(0,-1);
      
      if(this.bi.group.field != ''){
        executeSql = executeSql + groupByPart;
      }

      //判断排序是否为空
      for (const item of this.bi.order.field) {
        orderByPart += item + " " + this.bi.order.filter.type +",";
      }
      orderByPart = orderByPart.slice(0,-1);
      
      if(this.bi.order.field != ''){
        executeSql = executeSql + orderByPart;
      }

      console.log(executeSql)

      this.$set(this.database, 'executeSql', executeSql);

      this.database.chartStucture.legend = this.bi.legend.filter.value;
      this.database.chartStucture.coordinate = this.bi.coordinate.filter.value;
      this.database.chartStucture.statisticsType = this.bi.statistics.type;

      this.$set(this.configData.chartOption, 'database', JSON.parse(JSON.stringify( this.database )));
      this.$set(this.configData.chartOption, 'bi', JSON.parse(JSON.stringify( this.bi )));
      this.dbVisble = false;
    },
    //获取数据源列表
    getSourseList(){
        listSourse().then((response) => {      
          this.sourseList = response.rows;
        });
    },
    //连接数据库
    linkDB(){
     //必须选择数据源
      if(this.database.dataSourceId == ''){
       
       this.$message.error('请选择数据源');
       return false;
      
      }else{
        this.loading = true;
        getSourse(this.database.dataSourceId).then((response) => {
          
          //重新赋值
          this.database.type = response.data.databaseType;
          this.database.ipAdress = response.data.ipAddress ;
          this.database.port = response.data.port;
          this.database.baseName = response.data.databaseName;
          this.database.username = response.data.username;
          this.database.password = response.data.password;
          
          if (response.code == 200) {
      
            this.DBConn()
          }else{
            this.$message.error('连接数据库失败');
          }
                   
        });
      }
      
    },
    addSourse(){
       this.reset();
       this.sourseOpen = true;
    },
     // 取消按钮
    cancel() {
      this.sourseOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([]);
      }
      this.form = {
        id: undefined,
        databaseType: undefined,
        ipAddress: undefined,
        port: undefined,
        databaseName: undefined,
        linkName: undefined,
        username: undefined,
        password: undefined,
        remark: undefined,
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
            addSourse(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.sourseOpen = false;
                this.getSourseList();
              } else {
                this.msgError(response.msg);
              }
            });
          
        }
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.select-item {
  display: flex;
  border: 1px dashed #fff;
  box-sizing: border-box;
  & .close-btn {
    cursor: pointer;
    color: #f56c6c;
  }
  & .el-input + .el-input {
    margin-left: 4px;
  }
}
.el-input--medium .el-input__inner {
    height: 32px !important;
    width: 90px !important;
}
.el-form-item__label{
  width:30px
}
.select-item + .select-item {
  margin-top: 4px;
}
.select-item.sortable-chosen {
  border: 1px dashed #409eff;
}
.select-line-icon {
  line-height: 32px;
  font-size: 22px;
  padding: 0 4px;
  color: #777;
}

/deep/ .center-tabs .el-tabs__item {
    width: 33%;
    text-align: center;
}
.screen>:first-child{
  margin-top:37px
}
/**  滚动条凹槽的颜色，还可以设置边框属性  **/
::-webkit-scrollbar-track-piece { 

  background-color:#f8f8f8; 
  border-radius: 10px;
}
/** 滚动条的宽度  **/
::-webkit-scrollbar {

  width:9px;

  height:9px; 

}
/** 滚动条的设置  **/
::-webkit-scrollbar-thumb {

  background-color:#dddddd;

  background-clip:padding-box;

  min-height:28px; 
  border-radius: 10px;

}

::-webkit-scrollbar-thumb:hover {

  background-color:#bbb; 

}
</style>